#include "pyalgo.h"


InitSort g_sLib;

static PyObject* PyAlgoSort_SortAlgos(PyObject* self, PyObject* args)
{
    PyObject*   retobj = PyTuple_New(g_sLib.size());
    for(int i=0; i<g_sLib.size(); i++)
    {
        PyTuple_SetItem(retobj,i,PyString_FromString(g_sLib[i].c_str()));
    }
    PyObject* ret = (PyObject*)Py_BuildValue("O",retobj);
    return ret;
}

static PyObject* PyAlgoSort_Sort(PyObject* self, PyObject* args)
{
    char*       name;
    int*        data;
    int         len;
    double      res=0;
    PyObject*   paraobj;
    PyObject*   retobj;
    SortFunc    sort = 0;
    if(!PyArg_ParseTuple(args,"sOi",&name,&paraobj,&len))
        return NULL;
    if(sort = g_sLib[std::string(name)])
    {
        if(PyTuple_Check(paraobj))
        {
            data = new int[len];
            for(int i=0; i<len; i++)
            {
                PyObject* obj = PyTuple_GetItem(paraobj,i);
                data[i] = (int)PyInt_AsSsize_t(obj);
            }
            res = sort(data, len);



            retobj = PyTuple_New(len);
            for(int i=0; i<len; i++)
            {
                PyTuple_SetItem(retobj,i,PyInt_FromLong(data[i]));
            }
        }
        PyObject* ret = (PyObject*)Py_BuildValue("dO",res, retobj);
        delete data;
        return ret;
    }else
    {
        PyObject* ret = (PyObject*)Py_BuildValue("s" ,"can not find corresponding algorithm");
        return ret;
    }


}

static PyMethodDef PyAlgoMethods[] =
{
    {"Sort", PyAlgoSort_Sort, METH_VARARGS},
    {"SortAlgos", PyAlgoSort_SortAlgos, METH_VARARGS},
    {NULL, NULL},
};

PyMODINIT_FUNC initPyAlgoSort()
{
    Py_InitModule("PyAlgoSort", PyAlgoMethods);
}
